﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Configuration;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using LineWatch.Common;
using DBAccessLib;
using System.Globalization;
using System.IO;

namespace LineWatch_WinForm
{
    public partial class ProductManagementView : Form
    {
        private const string COMMAND_HEADER = "@00RD";

        PositionManagementView positionManagementView = new PositionManagementView();
        ScreenSaver screenSaver = null;

        private UserAndLineCodeModel userAndLineCodeModel = new UserAndLineCodeModel();

        private Dictionary<string, string> serialPortsAndLineCodes = new Dictionary<string, string>();
        private Dictionary<string, SerialPortOperator> lineCodesAndSerialPortOperators
                                                       = new Dictionary<string, SerialPortOperator>();

        private SerialPortOperator serialPortOperator1 = null;
        private SerialPortOperator serialPortOperator2 = null;
        private SerialPortOperator serialPortOperator3 = null;

        private string planNumPositionLine1 = string.Empty;
        private string productNumPositionLine1 = string.Empty;
        private string stopTimePositionLine1 = string.Empty;
        private string CTSignalDMPositionLine1 = string.Empty;
        private string CTTimeDMPositionLine1 = string.Empty;
        private string CTTimeLine1 = string.Empty;
        private DateTime currentNowPlanUpdatedTimeLine1 = DateTime.Now;

        private string planNumPositionLine2 = string.Empty;
        private string productNumPositionLine2 = string.Empty;
        private string stopTimePositionLine2 = string.Empty;
        private string CTSignalDMPositionLine2 = string.Empty;
        private string CTTimeDMPositionLine2 = string.Empty;
        private string CTTimeLine2 = string.Empty;
        private DateTime currentNowPlanUpdatedTimeLine2 = DateTime.Now;

        private string planNumPositionLine3 = string.Empty;
        private string productNumPositionLine3 = string.Empty;
        private string stopTimePositionLine3 = string.Empty;
        private string CTSignalDMPositionLine3 = string.Empty;
        private string CTTimeDMPositionLine3 = string.Empty;
        private string CTTimeLine3 = string.Empty;
        private DateTime currentNowPlanUpdatedTimeLine3 = DateTime.Now;

        private PositionCommandType currentPositionCommandTypeLine1 = PositionCommandType.AllProductData;
        private PositionCommandType currentPositionCommandTypeLine2 = PositionCommandType.AllProductData;
        private PositionCommandType currentPositionCommandTypeLine3 = PositionCommandType.AllProductData;

        private ProductInfoType productInfoTypeLine1 = ProductInfoType.AllProductInfo;
        private ProductInfoType productInfoTypeLine2 = ProductInfoType.AllProductInfo;
        private ProductInfoType productInfoTypeLine3 = ProductInfoType.AllProductInfo;

        // Position Management
        private int minPositionLine1 = 0;
        private int maxPositionLine1 = 0;
        private int currentStartPositionLine1 = 0;
        private int currentEndPositionLine1 = 0;

        private int minPositionLine2 = 0;
        private int maxPositionLine2 = 0;
        private int currentStartPositionLine2 = 0;
        private int currentEndPositionLine2 = 0;

        private int minPositionLine3 = 0;
        private int maxPositionLine3 = 0;
        private int currentStartPositionLine3 = 0;
        private int currentEndPositionLine3 = 0;

        private Dictionary<int, string> positionStatusLine1 = new Dictionary<int, string>();
        private Dictionary<int, string> positionStatusLine2 = new Dictionary<int, string>();
        private Dictionary<int, string> positionStatusLine3 = new Dictionary<int, string>();

        /// <summary>
        /// Constructor
        /// </summary>
        public ProductManagementView()
        {
            InitializeComponent();

            this.timer.Enabled = false;

            string defaultValue = "0";

            this.lblDayPlanLine1.Text = defaultValue;
            this.lblCurrentPlanLine1.Text = defaultValue;
            this.lblActualCompletedLine1.Text = defaultValue;
            this.lblStopTimeLine1.Text = defaultValue;

            this.lblDayPlanLine2.Text = defaultValue;
            this.lblCurrentPlanLine2.Text = defaultValue;
            this.lblActualCompletedLine2.Text = defaultValue;
            this.lblStopTimeLine2.Text = defaultValue;

            this.lblDayPlanLine3.Text = defaultValue;
            this.lblCurrentPlanLine3.Text = defaultValue;
            this.lblActualCompletedLine3.Text = defaultValue;
            this.lblStopTimeLine3.Text = defaultValue;

            this.InitFont();
        }

        /// <summary>
        /// Load
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void ProductManagementView_Load(object sender, EventArgs e)
        {
            this.GetUserAndLineCode();
            this.GetAllLines();
            this.InitOperationArea();
            this.InitDMPositionAndCommandType();

            this.minPositionLine1 = ConfigInfo.GetMinPosition(ConfigInfo.LineCode1);
            this.maxPositionLine1 = ConfigInfo.GetMaxPosition(ConfigInfo.LineCode1);
            this.currentStartPositionLine1 = this.minPositionLine1;
            this.currentEndPositionLine1 = this.minPositionLine1;

            this.minPositionLine2 = ConfigInfo.GetMinPosition(ConfigInfo.LineCode2);
            this.maxPositionLine2 = ConfigInfo.GetMaxPosition(ConfigInfo.LineCode2);
            this.currentStartPositionLine2 = this.minPositionLine2;
            this.currentEndPositionLine2 = this.minPositionLine2;

            this.minPositionLine3 = ConfigInfo.GetMinPosition(ConfigInfo.LineCode3);
            this.maxPositionLine3 = ConfigInfo.GetMaxPosition(ConfigInfo.LineCode3);
            this.currentStartPositionLine3 = this.minPositionLine3;
            this.currentEndPositionLine3 = this.minPositionLine3;
        }

        /// <summary>
        /// Shown
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void ProductManagementView_Shown(object sender, EventArgs e)
        {
            Util.PositionNormalTime = DateTime.Now;

            if (ConfigInfo.CurrentLineCodeCount >= 1)
            {
                // Send Line1 Data
                if (productInfoTypeLine1 == ProductInfoType.AllProductInfo)
                {
                    this.currentPositionCommandTypeLine1 = PositionCommandType.AllProductData;
                    this.serialPortOperator1.WriteLine(COMMAND_HEADER + planNumPositionLine1 + "0003");
                }
                else
                {
                    this.currentPositionCommandTypeLine1 = PositionCommandType.PlanNum;
                    this.serialPortOperator1.WriteLine(COMMAND_HEADER + planNumPositionLine1 + "0001");
                }
            }

            if (ConfigInfo.CurrentLineCodeCount >= 2)
            {
                // Send Line2 Data
                if (productInfoTypeLine2 == ProductInfoType.AllProductInfo)
                {
                    this.currentPositionCommandTypeLine2 = PositionCommandType.AllProductData;
                    this.serialPortOperator2.WriteLine(COMMAND_HEADER + planNumPositionLine2 + "0003");
                }
                else
                {
                    this.currentPositionCommandTypeLine2 = PositionCommandType.PlanNum;
                    this.serialPortOperator2.WriteLine(COMMAND_HEADER + planNumPositionLine2 + "0001");
                }
            }

            if (ConfigInfo.CurrentLineCodeCount >= 3)
            {
                // Send Line3 Data
                if (productInfoTypeLine3 == ProductInfoType.AllProductInfo)
                {
                    this.currentPositionCommandTypeLine3 = PositionCommandType.AllProductData;
                    this.serialPortOperator3.WriteLine(COMMAND_HEADER + planNumPositionLine3 + "0003");
                }
                else
                {
                    this.currentPositionCommandTypeLine3 = PositionCommandType.PlanNum;
                    this.serialPortOperator3.WriteLine(COMMAND_HEADER + planNumPositionLine3 + "0001");
                }
            }

            this.timer.Enabled = true;
        }

        /// <summary>
        /// Get User And Line Code
        /// </summary>
        private void GetUserAndLineCode()
        {
            this.userAndLineCodeModel = Account.GetUserAndLineCode(LoginInfo.UserName);
            ConfigInfo.CurrentLineCodeCount = this.userAndLineCodeModel.UserAndLineCodeTable.Rows.Count;
        }

        /// <summary>
        /// Get All Lines
        /// </summary>
        private void GetAllLines()
        {
            ConfigInfo.DtAllLines = Product.GetAllLines();
        }

        /// <summary>
        /// Init Operation Area
        /// </summary>
        private void InitOperationArea()
        {
            string productManagement = "生产管理看板";
            if (ConfigInfo.CurrentLineCodeCount <= 0)
            {
                this.tlpMain.Visible = false;
            }

            if (ConfigInfo.CurrentLineCodeCount >= 3)
            {
                ConfigInfo.LineCode3
                    = this.userAndLineCodeModel.UserAndLineCodeTable.Rows[2]["Flow"].ToString().Trim();

                string lineName3 = ConfigInfo.GetLineNameByCode(ConfigInfo.LineCode3);

                ConfigInfo.DtLineWatchSys3 = Config.GetLineWatchSys(ConfigInfo.LineCode3);

                //this.lblShiftLine3.Text = ConfigInfo.GetShiftInfo(ConfigInfo.DtLineWatchSys3);

                this.lblProductManagement3.Text = lineName3 + productManagement;

                this.tlpOperationArea1.Visible = true;
                this.tlpOperationArea2.Visible = true;
                this.tlpOperationArea3.Visible = true;

                this.tlpMain.ColumnStyles.Clear();
                this.tlpMain.ColumnStyles.Add(new System.Windows.Forms.ColumnStyle(System.Windows.Forms.SizeType.Absolute, 1F));
                this.tlpMain.ColumnStyles.Add(new System.Windows.Forms.ColumnStyle(System.Windows.Forms.SizeType.Percent, 50F));
                this.tlpMain.ColumnStyles.Add(new System.Windows.Forms.ColumnStyle(System.Windows.Forms.SizeType.Absolute, 1F));
                this.tlpMain.ColumnStyles.Add(new System.Windows.Forms.ColumnStyle(System.Windows.Forms.SizeType.Percent, 50F));
                this.tlpMain.ColumnStyles.Add(new System.Windows.Forms.ColumnStyle(System.Windows.Forms.SizeType.Absolute, 1F));
                this.tlpMain.ColumnStyles.Add(new System.Windows.Forms.ColumnStyle(System.Windows.Forms.SizeType.Percent, 50F));
                this.tlpMain.ColumnStyles.Add(new System.Windows.Forms.ColumnStyle(System.Windows.Forms.SizeType.Absolute, 1F));

                string serialPortName3 = ConfigInfo.GetLineSerialPortByCode(ConfigInfo.LineCode3);
                this.serialPortsAndLineCodes.Add(serialPortName3, ConfigInfo.LineCode3);

                try
                {
                    this.serialPortOperator3 = new SerialPortOperator();
                    this.Controls.Add(this.serialPortOperator3);
                    this.serialPortOperator3.InitPort(serialPortName3, 9600);
                    this.serialPortOperator3.InterfaceUpdateHandle
                               = new InterfaceUpdateHandler(InterfaceUpdate3);

                    this.lineCodesAndSerialPortOperators.Add(ConfigInfo.LineCode3, this.serialPortOperator3);
                }
                catch
                {

                }
            }

            if (ConfigInfo.CurrentLineCodeCount >= 2)
            {
                ConfigInfo.LineCode2
                    = this.userAndLineCodeModel.UserAndLineCodeTable.Rows[1]["Flow"].ToString().Trim();

                string lineName2 = ConfigInfo.GetLineNameByCode(ConfigInfo.LineCode2);

                ConfigInfo.DtLineWatchSys2 = Config.GetLineWatchSys(ConfigInfo.LineCode2);

                //this.lblShiftLine2.Text = ConfigInfo.GetShiftInfo(ConfigInfo.DtLineWatchSys2);

                this.lblProductManagement2.Text = lineName2 + productManagement;

                if (ConfigInfo.CurrentLineCodeCount == 2)
                {
                    this.tlpOperationArea1.Visible = true;
                    this.tlpOperationArea2.Visible = true;
                    this.tlpOperationArea3.Visible = false;

                    this.tlpMain.ColumnStyles.Clear();
                    this.tlpMain.ColumnStyles.Add(new System.Windows.Forms.ColumnStyle(System.Windows.Forms.SizeType.Absolute, 5F));
                    this.tlpMain.ColumnStyles.Add(new System.Windows.Forms.ColumnStyle(System.Windows.Forms.SizeType.Percent, 50F));
                    this.tlpMain.ColumnStyles.Add(new System.Windows.Forms.ColumnStyle(System.Windows.Forms.SizeType.Absolute, 10F));
                    this.tlpMain.ColumnStyles.Add(new System.Windows.Forms.ColumnStyle(System.Windows.Forms.SizeType.Percent, 50F));
                    this.tlpMain.ColumnStyles.Add(new System.Windows.Forms.ColumnStyle(System.Windows.Forms.SizeType.Absolute, 1F));
                    this.tlpMain.ColumnStyles.Add(new System.Windows.Forms.ColumnStyle(System.Windows.Forms.SizeType.Absolute, 1F));
                    this.tlpMain.ColumnStyles.Add(new System.Windows.Forms.ColumnStyle(System.Windows.Forms.SizeType.Absolute, 5F));
                }

                string serialPortName2 = ConfigInfo.GetLineSerialPortByCode(ConfigInfo.LineCode2);
                this.serialPortsAndLineCodes.Add(serialPortName2, ConfigInfo.LineCode2);

                try
                {
                    this.serialPortOperator2 = new SerialPortOperator();
                    this.Controls.Add(this.serialPortOperator2);
                    this.serialPortOperator2.InitPort(serialPortName2, 9600);
                    this.serialPortOperator2.InterfaceUpdateHandle
                               = new InterfaceUpdateHandler(InterfaceUpdate2);

                    this.lineCodesAndSerialPortOperators.Add(ConfigInfo.LineCode2, this.serialPortOperator2);
                }
                catch
                {

                }
            }

            if (ConfigInfo.CurrentLineCodeCount >= 1)
            {
                ConfigInfo.LineCode1
                    = this.userAndLineCodeModel.UserAndLineCodeTable.Rows[0]["Flow"].ToString().Trim();

                string lineName1 = ConfigInfo.GetLineNameByCode(ConfigInfo.LineCode1);

                ConfigInfo.DtLineWatchSys1 = Config.GetLineWatchSys(ConfigInfo.LineCode1);

                this.lblShiftLine1.Text = ConfigInfo.GetShiftInfo(ConfigInfo.DtLineWatchSys1);

                this.lblProductManagement1.Text = lineName1 + productManagement;

                if (ConfigInfo.CurrentLineCodeCount == 1)
                {
                    this.tlpOperationArea1.Visible = true;
                    this.tlpOperationArea2.Visible = false;
                    this.tlpOperationArea3.Visible = false;

                    this.tlpMain.ColumnStyles.Clear();
                    this.tlpMain.ColumnStyles.Add(new System.Windows.Forms.ColumnStyle(System.Windows.Forms.SizeType.Absolute, 30F));
                    this.tlpMain.ColumnStyles.Add(new System.Windows.Forms.ColumnStyle(System.Windows.Forms.SizeType.Percent, 100F));
                    this.tlpMain.ColumnStyles.Add(new System.Windows.Forms.ColumnStyle(System.Windows.Forms.SizeType.Absolute, 1F));
                    this.tlpMain.ColumnStyles.Add(new System.Windows.Forms.ColumnStyle(System.Windows.Forms.SizeType.Absolute, 1F));
                    this.tlpMain.ColumnStyles.Add(new System.Windows.Forms.ColumnStyle(System.Windows.Forms.SizeType.Absolute, 1F));
                    this.tlpMain.ColumnStyles.Add(new System.Windows.Forms.ColumnStyle(System.Windows.Forms.SizeType.Absolute, 1F));
                    this.tlpMain.ColumnStyles.Add(new System.Windows.Forms.ColumnStyle(System.Windows.Forms.SizeType.Absolute, 30F));
                }

                string serialPortName1 = ConfigInfo.GetLineSerialPortByCode(ConfigInfo.LineCode1);
                this.serialPortsAndLineCodes.Add(serialPortName1, ConfigInfo.LineCode1);

                try
                {
                    this.serialPortOperator1 = new SerialPortOperator();
                    this.Controls.Add(this.serialPortOperator1);
                    this.serialPortOperator1.InitPort(serialPortName1, 9600);
                    this.serialPortOperator1.InterfaceUpdateHandle
                               = new InterfaceUpdateHandler(InterfaceUpdate1);

                    this.lineCodesAndSerialPortOperators.Add(ConfigInfo.LineCode1, this.serialPortOperator1);
                }
                catch
                {

                }
            }
        }

        /// <summary>
        /// Init Font
        /// </summary>
        private void InitFont()
        {
            foreach (Control control in this.Controls)
            {
                if (control.GetType() == typeof(Label))
                {
                    Label lbl = (Label)control;
                    if (lbl.Tag != null)
                    {
                        this.UpdateFont(lbl);
                    }
                }

                InitFont(control);
            }
        }

        /// <summary>
        /// Init Font
        /// </summary>
        /// <param name="controlParent"></param>
        private void InitFont(Control controlParent)
        {
            foreach (Control control in controlParent.Controls)
            {
                if (control.GetType() == typeof(Label))
                {
                    Label lbl = (Label)control;
                    if (lbl.Tag != null)
                    {
                        this.UpdateFont(lbl);
                    }
                }

                InitFont(control);
            }
        }

        /// <summary>
        /// Update Font
        /// </summary>
        /// <param name="control"></param>
        private void UpdateFont(Control control)
        {
            if (control.Tag.ToString().StartsWith("FontSizeTitle"))
            {
                this.SetFont(control, "Microsoft YaHei", ConfigInfo.ProductFontSizeTitle, FontStyle.Bold);
            }
            else if (control.Tag.ToString().StartsWith("FontSizeCaption"))
            {
                this.SetFont(control, "Microsoft YaHei", ConfigInfo.ProductFontSizeCaption, FontStyle.Bold);
            }
            else if (control.Tag.ToString().StartsWith("FontSizeValue"))
            {
                this.SetFont(control, "Impact", ConfigInfo.ProductFontSizeValue, FontStyle.Regular);
            }
        }

        /// <summary>
        /// Set Font
        /// </summary>
        /// <param name="control"></param>
        /// <param name="familyName"></param>
        /// <param name="emSize"></param>
        /// <param name="style"></param>
        private void SetFont(Control control, string familyName, float emSize, FontStyle style)
        {
            control.Font = new System.Drawing.Font(familyName,
                                                   emSize,
                                                   style,
                                                   System.Drawing.GraphicsUnit.Point,
                                                   ((byte)(0))
                                                   );
        }

        /// <summary>
        /// Init DM Position And Command Type
        /// </summary>
        private void InitDMPositionAndCommandType()
        {
            this.planNumPositionLine1 = ConfigurationManager.AppSettings["PlanNumDMPositionLine1"].ToString().Trim();
            this.productNumPositionLine1 = ConfigurationManager.AppSettings["ProductNumDMPositionLine1"].ToString().Trim();
            this.stopTimePositionLine1 = ConfigurationManager.AppSettings["StopTimeDMPositionLine1"].ToString().Trim();
            this.CTSignalDMPositionLine1 = ConfigurationManager.AppSettings["CTSignalDMPositionLine1"].ToString().Trim();
            this.CTTimeDMPositionLine1 = ConfigurationManager.AppSettings["CTTimeDMPositionLine1"].ToString().Trim();

            this.planNumPositionLine2 = ConfigurationManager.AppSettings["PlanNumDMPositionLine2"].ToString().Trim();
            this.productNumPositionLine2 = ConfigurationManager.AppSettings["ProductNumDMPositionLine2"].ToString().Trim();
            this.stopTimePositionLine2 = ConfigurationManager.AppSettings["StopTimeDMPositionLine2"].ToString().Trim();
            this.CTSignalDMPositionLine2 = ConfigurationManager.AppSettings["CTSignalDMPositionLine2"].ToString().Trim();
            this.CTTimeDMPositionLine2 = ConfigurationManager.AppSettings["CTTimeDMPositionLine2"].ToString().Trim();

            this.planNumPositionLine3 = ConfigurationManager.AppSettings["PlanNumDMPositionLine3"].ToString().Trim();
            this.productNumPositionLine3 = ConfigurationManager.AppSettings["ProductNumDMPositionLine3"].ToString().Trim();
            this.stopTimePositionLine3 = ConfigurationManager.AppSettings["StopTimeDMPositionLine3"].ToString().Trim();
            this.CTSignalDMPositionLine3 = ConfigurationManager.AppSettings["CTSignalDMPositionLine3"].ToString().Trim();
            this.CTTimeDMPositionLine3 = ConfigurationManager.AppSettings["CTTimeDMPositionLine3"].ToString().Trim();

            // Init Line1 Status
            int planNumPositionTemp = int.Parse(this.planNumPositionLine1);
            int productNumPositionTemp = int.Parse(this.productNumPositionLine1);
            int stopTimePositionTemp = int.Parse(this.stopTimePositionLine1);

            if ((planNumPositionTemp + 1 == productNumPositionTemp)
                && (planNumPositionTemp + 2 == stopTimePositionTemp))
            {
                this.currentPositionCommandTypeLine1 = PositionCommandType.AllProductData;
                this.productInfoTypeLine1 = ProductInfoType.AllProductInfo;
            }
            else
            {
                this.currentPositionCommandTypeLine1 = PositionCommandType.PlanNum;
                this.productInfoTypeLine1 = ProductInfoType.SingleProdutInfo;
            }

            // Init Line2 Status
            planNumPositionTemp = int.Parse(this.planNumPositionLine2);
            productNumPositionTemp = int.Parse(this.productNumPositionLine2);
            stopTimePositionTemp = int.Parse(this.stopTimePositionLine2);

            if ((planNumPositionTemp + 1 == productNumPositionTemp)
                && (planNumPositionTemp + 2 == stopTimePositionTemp))
            {
                this.currentPositionCommandTypeLine2 = PositionCommandType.AllProductData;
                this.productInfoTypeLine2 = ProductInfoType.AllProductInfo;
            }
            else
            {
                this.currentPositionCommandTypeLine2 = PositionCommandType.PlanNum;
                this.productInfoTypeLine2 = ProductInfoType.SingleProdutInfo;
            }

            // Init Line3 Status
            planNumPositionTemp = int.Parse(this.planNumPositionLine3);
            productNumPositionTemp = int.Parse(this.productNumPositionLine3);
            stopTimePositionTemp = int.Parse(this.stopTimePositionLine3);

            if ((planNumPositionTemp + 1 == productNumPositionTemp)
                && (planNumPositionTemp + 2 == stopTimePositionTemp))
            {
                this.currentPositionCommandTypeLine3 = PositionCommandType.AllProductData;
                this.productInfoTypeLine3 = ProductInfoType.AllProductInfo;
            }
            else
            {
                this.currentPositionCommandTypeLine3 = PositionCommandType.PlanNum;
                this.productInfoTypeLine3 = ProductInfoType.SingleProdutInfo;
            }
        }

        /// <summary>
        /// Interface Update 1
        /// </summary>
        /// <param name="text"></param>
        /// <param name="portName"></param>
        private void InterfaceUpdate1(string text, string portName)
        {
            this.ResolveDataAndSendCommand(text, portName,
                                           ref this.currentPositionCommandTypeLine1,
                                           this.productInfoTypeLine1,
                                           this.serialPortOperator1,
                                           this.planNumPositionLine1,
                                           this.productNumPositionLine1,
                                           this.stopTimePositionLine1,
                                           this.CTTimeDMPositionLine1,
                                           this.CTSignalDMPositionLine1,
                                           ref this.CTTimeLine1,
                                           this.minPositionLine1,
                                           this.maxPositionLine1,
                                           ref this.currentStartPositionLine1,
                                           ref this.currentEndPositionLine1,
                                           this.positionStatusLine1
                                           );
        }

        /// <summary>
        /// Interface Update 2
        /// </summary>
        /// <param name="text"></param>
        /// <param name="portName"></param>
        private void InterfaceUpdate2(string text, string portName)
        {
            this.ResolveDataAndSendCommand(text, portName,
                                           ref this.currentPositionCommandTypeLine2,
                                           this.productInfoTypeLine2,
                                           this.serialPortOperator2,
                                           this.planNumPositionLine2,
                                           this.productNumPositionLine2,
                                           this.stopTimePositionLine2,
                                           this.CTTimeDMPositionLine2,
                                           this.CTSignalDMPositionLine2,
                                           ref this.CTTimeLine2,
                                           this.minPositionLine2,
                                           this.maxPositionLine2,
                                           ref this.currentStartPositionLine2,
                                           ref this.currentEndPositionLine2,
                                           this.positionStatusLine2
                                           );
        }

        /// <summary>
        /// Interface Update 3
        /// </summary>
        /// <param name="text"></param>
        /// <param name="portName"></param>
        private void InterfaceUpdate3(string text, string portName)
        {
            this.ResolveDataAndSendCommand(text, portName,
                                           ref this.currentPositionCommandTypeLine3,
                                           this.productInfoTypeLine3,
                                           this.serialPortOperator3,
                                           this.planNumPositionLine3,
                                           this.productNumPositionLine3,
                                           this.stopTimePositionLine3,
                                           this.CTTimeDMPositionLine3,
                                           this.CTSignalDMPositionLine3,
                                           ref this.CTTimeLine3,
                                           this.minPositionLine3,
                                           this.maxPositionLine3,
                                           ref this.currentStartPositionLine3,
                                           ref this.currentEndPositionLine3,
                                           this.positionStatusLine3
                                           );
        }

        /// <summary>
        /// Resolve Data And Send Command
        /// </summary>
        /// <param name="text"></param>
        /// <param name="portName"></param>
        /// <param name="currentPositionCommandType"></param>
        /// <param name="productInfoType"></param>
        /// <param name="serialPortOperator"></param>
        /// <param name="planNumPosition"></param>
        /// <param name="productNumPosition"></param>
        /// <param name="stopTimePosition"></param>
        /// <param name="maxPosition"></param>
        /// <param name="currentStartPosition"></param>
        /// <param name="currentEndPosition"></param>
        /// <param name="positionStatus"></param>
        private void ResolveDataAndSendCommand(string text, string portName,
                                               ref PositionCommandType currentPositionCommandType,
                                               ProductInfoType productInfoType,
                                               SerialPortOperator serialPortOperator,
                                               string planNumPosition,
                                               string productNumPosition,
                                               string stopTimePosition,
                                               string CTTimeDMPosition,
                                               string CTSignalDMPosition,
                                               ref string CTTime,
                                               int minPosition,
                                               int maxPosition,
                                               ref int currentStartPosition,
                                               ref int currentEndPosition,
                                               Dictionary<int, string> positionStatus)
        {
            if (currentPositionCommandType == PositionCommandType.AllProductData)
            {
                int planNumGroupIndex = 1;
                int productNumGroupIndex = 2;
                int stopTimeGroupIndex = 3;

                string planNum = this.GetProductDataByGroup(text, planNumGroupIndex);
                string productNum = this.GetProductDataByGroup(text, productNumGroupIndex);
                string stopTime = this.GetProductDataByGroup(text, stopTimeGroupIndex);

                this.UpdateUI(planNum, productNum, stopTime, portName);

                currentPositionCommandType = PositionCommandType.CTTime;
                serialPortOperator.WriteLine(COMMAND_HEADER + CTTimeDMPosition + "0001");


                ////currentPositionCommandType = PositionCommandType.PositionSHA;
                ////serialPortOperator.WriteLine(COMMAND_HEADER
                ////                             + currentStartPosition.ToString("0000")
                ////                             + ConfigInfo.PositionNumInOneCommand.ToString("0000"));

                ////currentEndPosition = currentStartPosition + ConfigInfo.PositionNumInOneCommand - 1;
            }
            else if (currentPositionCommandType == PositionCommandType.PlanNum)
            {
                int planNumGroupIndex = 1;

                string planNum = this.GetProductDataByGroup(text, planNumGroupIndex);
                string productNum = string.Empty;
                string stopTime = string.Empty;

                this.UpdateUI(planNum, productNum, stopTime, portName);

                currentPositionCommandType = PositionCommandType.ProductNum;
                serialPortOperator.WriteLine(COMMAND_HEADER + productNumPosition + "0001");
            }
            else if (currentPositionCommandType == PositionCommandType.ProductNum)
            {
                int productNumGroupIndex = 1;

                string planNum = string.Empty;
                string productNum = this.GetProductDataByGroup(text, productNumGroupIndex);
                string stopTime = string.Empty;

                this.UpdateUI(planNum, productNum, stopTime, portName);

                currentPositionCommandType = PositionCommandType.StopTime;
                serialPortOperator.WriteLine(COMMAND_HEADER + stopTimePosition + "0001");
            }
            else if (currentPositionCommandType == PositionCommandType.StopTime)
            {
                int stopTimeGroupIndex = 1;

                string planNum = string.Empty;
                string productNum = string.Empty;
                string stopTime = this.GetProductDataByGroup(text, stopTimeGroupIndex);

                this.UpdateUI(planNum, productNum, stopTime, portName);

                currentPositionCommandType = PositionCommandType.CTTime;
                serialPortOperator.WriteLine(COMMAND_HEADER + CTTimeDMPosition + "0001");


                ////currentPositionCommandType = PositionCommandType.PositionSHA;

                ////serialPortOperator.WriteLine(COMMAND_HEADER
                ////                             + currentStartPosition.ToString("0000")
                ////                             + ConfigInfo.PositionNumInOneCommand.ToString("0000"));

                ////currentEndPosition = currentStartPosition + ConfigInfo.PositionNumInOneCommand - 1;
            }
            else if (currentPositionCommandType == PositionCommandType.CTTime)
            {
                int groupIndex = 1;

                CTTime = this.GetProductDataByGroup(text, groupIndex);

                currentPositionCommandType = PositionCommandType.CTSignal;
                serialPortOperator.WriteLine(COMMAND_HEADER + CTSignalDMPosition + "0001");
            }
            else if (currentPositionCommandType == PositionCommandType.CTSignal)
            {
                int groupIndex = 1;

                string CTSignal = this.GetProductDataByGroup(text, groupIndex);

                this.UpdateNowPlanUI(CTTime, CTSignal, portName);

                currentPositionCommandType = PositionCommandType.PositionSHA;

                serialPortOperator.WriteLine(COMMAND_HEADER
                                             + currentStartPosition.ToString("0000")
                                             + ConfigInfo.PositionNumInOneCommand.ToString("0000"));

                currentEndPosition = currentStartPosition + ConfigInfo.PositionNumInOneCommand - 1;
            }
            else if (currentPositionCommandType == PositionCommandType.PositionSHA)
            {
                this.GetPositionStatus(text, currentStartPosition, currentEndPosition, positionStatus);

                // Update Position Management Form
                this.UpdatePositionUI(positionStatus, portName);

                if (currentEndPosition >= maxPosition)
                {
                    currentEndPosition = minPosition;
                    currentStartPosition = minPosition;
                    if (productInfoType == ProductInfoType.AllProductInfo)
                    {
                        currentPositionCommandType = PositionCommandType.AllProductData;
                        serialPortOperator.WriteLine(COMMAND_HEADER + planNumPosition + "0003");
                    }
                    else
                    {
                        currentPositionCommandType = PositionCommandType.PlanNum;
                        serialPortOperator.WriteLine(COMMAND_HEADER + planNumPosition + "0001");
                    }
                }
                else
                {
                    currentStartPosition = currentEndPosition + 1;
                    currentPositionCommandType = PositionCommandType.PositionSHA;
                    serialPortOperator.WriteLine(COMMAND_HEADER
                                                 + currentStartPosition.ToString("0000")
                                                 + ConfigInfo.PositionNumInOneCommand.ToString("0000"));

                    currentEndPosition = currentStartPosition + ConfigInfo.PositionNumInOneCommand - 1;
                }
            }
        }

        /// <summary>
        /// Update UI
        /// </summary>
        /// <param name="text"></param>
        /// <param name="portName"></param>
        private void UpdateUI(string planNum, string productNum, string stopTime, string portName)
        {
            long planNumber = -1;
            long productNumber = -1;
            long stopTimeNumber = -1;
            long temp = 0;

            if (long.TryParse(planNum, NumberStyles.HexNumber, CultureInfo.CurrentCulture, out temp))
            {
                long.TryParse(planNum, NumberStyles.HexNumber, CultureInfo.CurrentCulture, out planNumber);
            }

            if (long.TryParse(productNum, NumberStyles.HexNumber, CultureInfo.CurrentCulture, out temp))
            {
                long.TryParse(productNum, NumberStyles.HexNumber, CultureInfo.CurrentCulture, out productNumber);
            }

            if (long.TryParse(stopTime, NumberStyles.HexNumber, CultureInfo.CurrentCulture, out temp))
            {
                long.TryParse(stopTime, NumberStyles.HexNumber, CultureInfo.CurrentCulture, out stopTimeNumber);
            }

            string lineCode = this.serialPortsAndLineCodes[portName];
            this.UpdateProductInfo(planNumber, productNumber, (stopTimeNumber == -1 ? -1 : (stopTimeNumber / 60)), lineCode);
        }

        /// <summary>
        /// Update Product Info
        /// </summary>
        /// <param name="lineCode"></param>
        /// <param name="planNum"></param>
        /// <param name="productNum"></param>
        /// <param name="stopTime"></param>
        private void UpdateProductInfo(long planNum, long productNum, long stopTime, string lineCode)
        {
            if (string.Equals(ConfigInfo.LineCode1, lineCode))
            {
                if (planNum >= 0)
                {
                    this.lblDayPlanLine1.Text = planNum.ToString();
                    ////this.lblCurrentPlanLine1.Text
                    ////    = ConfigInfo.GetNowPlanInfo(ConfigInfo.DtLineWatchSys1, planNum);
                }

                if (productNum >= 0)
                {
                    this.lblActualCompletedLine1.Text = productNum.ToString();
                }

                if (stopTime >= 0)
                {
                    this.lblStopTimeLine1.Text = stopTime.ToString();
                }
            }

            if (string.Equals(ConfigInfo.LineCode2, lineCode))
            {
                if (planNum >= 0)
                {
                    this.lblDayPlanLine2.Text = planNum.ToString();
                    ////this.lblCurrentPlanLine2.Text
                    ////    = ConfigInfo.GetNowPlanInfo(ConfigInfo.DtLineWatchSys2, planNum);
                }

                if (productNum >= 0)
                {
                    this.lblActualCompletedLine2.Text = productNum.ToString();
                }

                if (stopTime >= 0)
                {
                    this.lblStopTimeLine2.Text = stopTime.ToString();
                }
            }

            if (string.Equals(ConfigInfo.LineCode3, lineCode))
            {
                if (planNum >= 0)
                {
                    this.lblDayPlanLine3.Text = planNum.ToString();
                    ////this.lblCurrentPlanLine3.Text
                    ////    = ConfigInfo.GetNowPlanInfo(ConfigInfo.DtLineWatchSys3, planNum);
                }

                if (productNum >= 0)
                {
                    this.lblActualCompletedLine3.Text = productNum.ToString();
                }

                if (stopTime >= 0)
                {
                    this.lblStopTimeLine3.Text = stopTime.ToString();
                }
            }

            this.Refresh();
            this.Update();
        }

        /// <summary>
        /// Update Now Plan UI
        /// </summary>
        /// <param name="CTTime"></param>
        /// <param name="CTSignal"></param>
        /// <param name="portName"></param>
        private void UpdateNowPlanUI(string CTTime, string CTSignal, string portName)
        {
            long CTTimeNumber = -1;
            long CTSignalNumber = -1;

            long temp = 0;

            if (long.TryParse(CTTime, NumberStyles.HexNumber, CultureInfo.CurrentCulture, out temp))
            {
                long.TryParse(CTTime, NumberStyles.HexNumber, CultureInfo.CurrentCulture, out CTTimeNumber);
            }

            if (long.TryParse(CTSignal, NumberStyles.HexNumber, CultureInfo.CurrentCulture, out temp))
            {
                long.TryParse(CTSignal, NumberStyles.HexNumber, CultureInfo.CurrentCulture, out CTSignalNumber);
            }

            string lineCode = this.serialPortsAndLineCodes[portName];
            this.UpdateNowPlanInfo(CTTimeNumber, CTSignalNumber, lineCode);
        }

        /// <summary>
        /// Update Now Plan Info
        /// </summary>
        /// <param name="CTTime"></param>
        /// <param name="CTSignal"></param>
        /// <param name="lineCode"></param>
        private void UpdateNowPlanInfo(long CTTime, long CTSignal,  string lineCode)
        {
            if (CTSignal == 1)
            {
                if (string.Equals(ConfigInfo.LineCode1, lineCode))
                {
                    if ((DateTime.Now - this.currentNowPlanUpdatedTimeLine1).TotalSeconds >= CTTime)
                    {
                        string nowPlanTemp = this.lblCurrentPlanLine1.Text.Trim();
                        long nowPlan = 0;

                        long.TryParse(nowPlanTemp, out nowPlan);
                        nowPlan++;

                        this.lblCurrentPlanLine1.Text = nowPlan.ToString();
                        this.currentNowPlanUpdatedTimeLine1 = DateTime.Now;
                    }
                }

                if (string.Equals(ConfigInfo.LineCode2, lineCode))
                {
                    if ((DateTime.Now - this.currentNowPlanUpdatedTimeLine2).TotalSeconds >= CTTime)
                    {
                        string nowPlanTemp = this.lblCurrentPlanLine2.Text.Trim();
                        long nowPlan = 0;

                        long.TryParse(nowPlanTemp, out nowPlan);
                        nowPlan++;

                        this.lblCurrentPlanLine2.Text = nowPlan.ToString();
                        this.currentNowPlanUpdatedTimeLine2 = DateTime.Now;
                    }
                }

                if (string.Equals(ConfigInfo.LineCode3, lineCode))
                {
                    if ((DateTime.Now - this.currentNowPlanUpdatedTimeLine3).TotalSeconds >= CTTime)
                    {
                        string nowPlanTemp = this.lblCurrentPlanLine3.Text.Trim();
                        long nowPlan = 0;

                        long.TryParse(nowPlanTemp, out nowPlan);
                        nowPlan++;

                        this.lblCurrentPlanLine3.Text = nowPlan.ToString();
                        this.currentNowPlanUpdatedTimeLine3 = DateTime.Now;
                    }
                }

                this.Refresh();
                this.Update();
            }
        }

        /// <summary>
        /// Get Product Data By Group
        /// </summary>
        /// <param name="text"></param>
        /// <param name="groupIndex"></param>
        /// <returns></returns>
        private string GetProductDataByGroup(string text, int groupIndex)
        {
            if (groupIndex == 1)
            {
                return text.Substring(0, 4);
            }

            if (groupIndex == 2) return text.Substring(4, 4);

            if (groupIndex == 3)
            {
                return text.Substring(8, 4);
            }

            return string.Empty;
        }

        /// <summary>
        /// Update Position UI
        /// </summary>
        /// <param name="positionStatus"></param>
        /// <param name="portName"></param>
        private void UpdatePositionUI(Dictionary<int, string> positionStatus, string portName)
        {
            if (this.positionManagementView == null)
            {
                this.positionManagementView = new PositionManagementView();
            }

            string lineCode = this.serialPortsAndLineCodes[portName];
            this.positionManagementView.UpdatePositionInfo(positionStatus, lineCode);

            if (this.positionManagementView.HasSHAPosition())
            {
                if (this.screenSaver != null)
                {
                    this.screenSaver.Close();
                }

                Util.PositionNormalTime = DateTime.MaxValue;

                if (this.positionManagementView == null)
                {
                    this.positionManagementView = new PositionManagementView();
                }

                if (this.positionManagementView.IsDisposed)
                {
                    this.positionManagementView = new PositionManagementView();
                }

                this.positionManagementView.Show();
                this.positionManagementView.BringToFront();
                this.positionManagementView.Focus();
            }
            else
            {
                if (Util.PositionNormalTime == DateTime.MaxValue)
                {
                    Util.PositionNormalTime = DateTime.Now;
                }

                this.positionManagementView.Hide();
            }
        }

        /// <summary>
        /// Get Position Status
        /// </summary>
        /// <param name="text"></param>
        /// <param name="currentStartPosition"></param>
        /// <param name="currentEndPosition"></param>
        /// <param name="positionStatus"></param>
        private void GetPositionStatus(string status,
                                       int currentStartPosition,
                                       int currentEndPosition,
                                       Dictionary<int, string> positionStatus)
        {
            for (int position = currentStartPosition; position <= currentEndPosition; position++)
            {
                if (status.Length >= 4)
                {
                    if (!positionStatus.ContainsKey(position))
                    {
                        positionStatus.Add(position, status.Substring(0, 4));
                    }
                    else
                    {
                        positionStatus[position] = status.Substring(0, 4);
                    }

                    if (status.Length > 4)
                    {
                        status = status.Substring(4, status.Length - 4);
                    }
                    else
                    {
                        status = string.Empty;
                        break;
                    }
                }
            }
        }

        /// <summary>
        /// Change Shift Name and Update Product Log
        /// </summary>
        /// <returns></returns>
        private bool ChangeShiftNameAndUpdateProductLog()
        {
            bool isShiftNameChanged = false;

            string shiftInfoLine1 = string.Empty;
            string shiftInfoLine2 = string.Empty;
            string shiftInfoLine3 = string.Empty;

            if (ConfigInfo.CurrentLineCodeCount >= 1)
            {
                shiftInfoLine1 = ConfigInfo.GetShiftInfo(ConfigInfo.DtLineWatchSys1);

                if (!string.Equals(this.lblShiftLine1.Text.Trim(), shiftInfoLine1.Trim()))
                {
                    isShiftNameChanged = true;
                    this.lblCurrentPlanLine1.Text = "0";
                    this.currentNowPlanUpdatedTimeLine1 = DateTime.Now;
                }
            }

            if (ConfigInfo.CurrentLineCodeCount >= 2)
            {
                shiftInfoLine2 = ConfigInfo.GetShiftInfo(ConfigInfo.DtLineWatchSys2);

                if (!string.Equals(this.lblShiftLine2.Text.Trim(), shiftInfoLine2.Trim()))
                {
                    isShiftNameChanged = true;
                    this.lblCurrentPlanLine2.Text = "0";
                    this.currentNowPlanUpdatedTimeLine2 = DateTime.Now;
                }
            }

            if (ConfigInfo.CurrentLineCodeCount >= 3)
            {
                shiftInfoLine3 = ConfigInfo.GetShiftInfo(ConfigInfo.DtLineWatchSys3);

                if (!string.Equals(this.lblShiftLine3.Text.Trim(), shiftInfoLine3.Trim()))
                {
                    isShiftNameChanged = true;
                    this.lblCurrentPlanLine3.Text = "0";
                    this.currentNowPlanUpdatedTimeLine3 = DateTime.Now;
                }
            }

            if (isShiftNameChanged)
            {
                this.UpdateProductLog();

                this.lblShiftLine1.Text = shiftInfoLine1.Trim();
                this.lblShiftLine2.Text = shiftInfoLine2.Trim();
                this.lblShiftLine3.Text = shiftInfoLine3.Trim();
            }

            return isShiftNameChanged;
        }

        /// <summary>
        /// Get Shift
        /// </summary>
        /// <param name="text"></param>
        /// <returns></returns>
        private string GetShift(string text)
        {
            if (text.Contains("1"))
            {
                return "1";
            }
            else if (text.Contains("2"))
            {
                return "2";
            }

            return "0";
        }

        /// <summary>
        /// Update Product Log
        /// </summary>
        private void UpdateProductLog()
        {
            string logDate = DateTime.Now.Date.ToString("yyyy-MM-dd");

            if (ConfigInfo.CurrentLineCodeCount >= 1)
            {
                string shift = this.GetShift(this.lblShiftLine1.Text);
                Product.UpdateProductLogByKey(ConfigInfo.LineCode1,
                                              shift,
                                              logDate,
                                              this.lblDayPlanLine1.Text,
                                              this.lblCurrentPlanLine1.Text,
                                              this.lblActualCompletedLine1.Text,
                                              this.lblStopTimeLine1.Text);
            }

            if (ConfigInfo.CurrentLineCodeCount >= 2)
            {
                string shift = this.GetShift(this.lblShiftLine2.Text);
                Product.UpdateProductLogByKey(ConfigInfo.LineCode2,
                                              shift,
                                              logDate,
                                              this.lblDayPlanLine2.Text,
                                              this.lblCurrentPlanLine2.Text,
                                              this.lblActualCompletedLine2.Text,
                                              this.lblStopTimeLine2.Text);
            }

            if (ConfigInfo.CurrentLineCodeCount >= 3)
            {
                string shift = this.GetShift(this.lblShiftLine3.Text);
                Product.UpdateProductLogByKey(ConfigInfo.LineCode3,
                                              shift,
                                              logDate,
                                              this.lblDayPlanLine3.Text,
                                              this.lblCurrentPlanLine3.Text,
                                              this.lblActualCompletedLine3.Text,
                                              this.lblStopTimeLine3.Text);
            }
        }

        /// <summary>
        /// Show Screen Saver
        /// </summary>
        private void ShowScreenSaver()
        {
            if (this.screenSaver == null)
            {
                this.screenSaver = new ScreenSaver();
            }

            if (this.screenSaver.IsDisposed)
            {
                this.screenSaver = new ScreenSaver();
            }

            if (!this.screenSaver.Visible)
            {
                this.screenSaver.ShowDialog();
            }
        }

        /// <summary>
        /// timer Tick
        /// for Screen Saver
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void timer_Tick(object sender, EventArgs e)
        {
            this.ChangeShiftNameAndUpdateProductLog();

            int timeSpan = ConfigInfo.GetScreenTimeSpan1(ConfigInfo.DtLineWatchSys1);

            if (timeSpan <= 0)
            {
                return;
            }

            TimeSpan span = DateTime.Now - Util.PositionNormalTime;

            if (span.TotalSeconds >= timeSpan)
            {
                this.ShowScreenSaver();
            }
        }

        /// <summary>
        /// Qiut
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void btnQuit_Click(object sender, EventArgs e)
        {
            try
            {
                foreach (SerialPortOperator serialPortOperator in this.lineCodesAndSerialPortOperators.Values)
                {
                    serialPortOperator.ClosePort();
                }
            }
            catch
            {

            }

            try
            {
                if (this.positionManagementView == null)
                {
                    this.positionManagementView.Close();
                }
            }
            catch
            {

            }

            this.Close();

            Application.Exit();
        }

        /// <summary>
        /// Form Closing
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void ProductManagementView_FormClosing(object sender, FormClosingEventArgs e)
        {
            try
            {
                this.UpdateProductLog();
            }
            catch
            {

            }

            try
            {
                foreach (SerialPortOperator serialPortOperator in this.lineCodesAndSerialPortOperators.Values)
                {
                    serialPortOperator.ClosePort();
                }
            }
            catch
            {

            }
        }

        private void btnLoad_Click(object sender, EventArgs e)
        {
            Stream myStream;
            OpenFileDialog openFileDialog1 = new OpenFileDialog();

            openFileDialog1.InitialDirectory = "c:\\";
            openFileDialog1.Filter = "txt files (*.csv)|*.csv";
            openFileDialog1.FilterIndex = 1;
            openFileDialog1.RestoreDirectory = true;

            if (openFileDialog1.ShowDialog() == DialogResult.OK)
            {
                if ((myStream = openFileDialog1.OpenFile()) != null)
                {
                    if (myStream == null)
                    {
                        return;
                    }
                }
                else
                {
                    return;
                }
            }
            else
            {
                return;
            }

            LinePositionModel model = new LinePositionModel();
            model.LinePositionTable = ConfigInfo.DtAllPositions.Clone();

            //create object of CSVReader and pass the stream

            Encoding encoding = Encoding.GetEncoding(ConfigurationManager.AppSettings["CSVEncoding"]);
            CSVReader reader = new CSVReader(myStream, encoding);

            string[] data = new string[100];
            int lineIndex = 0;

            while ((data = reader.GetCSVLine()) != null)
            {
                lineIndex++;
                if (lineIndex == 1)
                {
                    continue;
                }

                if (data.Length >= 5)
                {
                    DataRow newRow = model.LinePositionTable.NewRow();

                    newRow["Line_Code"] = data[0].Trim();
                    newRow["SPositionID"] = data[1].Trim();
                    newRow["FPositionID"] = data[2].Trim();
                    newRow["Position"] = data[3].Trim();
                    newRow["SetDate"] = string.Empty;
                    newRow["User"] = string.Empty;

                    if (!string.IsNullOrWhiteSpace(data[4].Trim()))
                    {
                        newRow["Content1"] = data[4].Trim();
                        newRow["Content2"] = "1";
                        newRow["Content3"] = "0";
                        newRow["Content4"] = "0";
                    }
                    else if ((data.Length >= 6) && !string.IsNullOrWhiteSpace(data[5].Trim()))
                    {
                        newRow["Content1"] = data[5].Trim();
                        newRow["Content2"] = "0";
                        newRow["Content3"] = "1";
                        newRow["Content4"] = "0";
                    }
                    else if ((data.Length >= 7) && !string.IsNullOrWhiteSpace(data[6].Trim()))
                    {
                        newRow["Content1"] = data[6].Trim();
                        newRow["Content2"] = "0";
                        newRow["Content3"] = "0";
                        newRow["Content4"] = "1";
                    }

                    newRow["Content5"] = string.Empty;
                    newRow["Content6"] = string.Empty;
                    model.LinePositionTable.Rows.Add(newRow);
                }
            }

            bool result = Position.SaveAllLinePositions(model);

            if (result)
            {
                MessageBox.Show("保存成功!", "保存", MessageBoxButtons.OK, MessageBoxIcon.Information);
            }
            else
            {
                MessageBox.Show("保存失败!", "保存", MessageBoxButtons.OK, MessageBoxIcon.Error);
            }

            if (myStream != null)
            {
                myStream.Close();
            }
        }

        private void Reset_Click(object sender, EventArgs e)
        {
            string dmPlan1 = ConfigurationManager.AppSettings["PlanNumDMPositionLine1"];
            string dmProd1 = ConfigurationManager.AppSettings["ProductNumDMPositionLine1"];
            string dmStop1 = ConfigurationManager.AppSettings["StopTimeDMPositionLine1"];
            string dmPlan2 = ConfigurationManager.AppSettings["PlanNumDMPositionLine2"];
            string dmProd2 = ConfigurationManager.AppSettings["ProductNumDMPositionLine2"];
            string dmStop2 = ConfigurationManager.AppSettings["StopTimeDMPositionLine2"];
            string dmPlan3 = ConfigurationManager.AppSettings["PlanNumDMPositionLine3"];
            string dmProd3 = ConfigurationManager.AppSettings["ProductNumDMPositionLine3"];
            string dmStop3 = ConfigurationManager.AppSettings["StopTimeDMPositionLine3"];

            if (ConfigInfo.CurrentLineCodeCount >= 1)
            {
                ResetDMValues(dmPlan1, 1);
                ResetDMValues(dmProd1, 1);
                ResetDMValues(dmStop1, 1);
            }
            if (ConfigInfo.CurrentLineCodeCount >= 2)
            {
                ResetDMValues(dmPlan2, 2);
                ResetDMValues(dmProd2, 2);
                ResetDMValues(dmStop2, 2);
            }
            if (ConfigInfo.CurrentLineCodeCount >= 3)
            {
                ResetDMValues(dmPlan3, 3);
                ResetDMValues(dmProd3, 3);
                ResetDMValues(dmStop3, 3);
            }

        }

        private void ResetDMValues(string dmPlan1, int groupIndex)
        {
            //if (groupIndex == 1) this.serialPortOperator1.WriteDM(dmPlan1, "0");
            //if (groupIndex == 2) this.serialPortOperator2.WriteDM(dmPlan1, "0");
            //if (groupIndex == 3) this.serialPortOperator3.WriteDM(dmPlan1, "0");
        }

        private void button1_Click(object sender, EventArgs e)
        {
            //SetupPlanNum form = new SetupPlanNum();
            //if (ConfigInfo.CurrentLineCodeCount >= 1)
            //{
            //    form.SP = this.serialPortOperator1;
            //}

            //if (ConfigInfo.CurrentLineCodeCount >= 2)
            //{
            //}
            //if (ConfigInfo.CurrentLineCodeCount >= 3)
            //{
            //}
            //form.ShowDialog();
        }
    }
}
